<?php

/**
 * 购物流程
 *
 * @author birdy <freebirdy@foxmail.com>
 * @link http://www.aiyuangong.com
 */
namespace app\member\controller;

use think\Validate;

class Buy extends \app\common\controller\Member
{

    public function step2()
    {
        $this->assign('step', 'step2');
        
        $buy_to_ehr = input('post.buy_to_ehr') ? true : false;
        if ($buy_to_ehr) {
            $return_url = config('ucenter.url').'/inspage/main.html#/insurance/home/index/';
            $url = rpc('member/member/get_sso_url', [$this->member_info['mobile'], $return_url]);
            return redirect($url ? : '/');
        }
        
        $ifcart = input('post.ifcart') ? true : false;
        $cart_id = input('post.cart_id/a');
        
        // 得到购买数据
        $logic_buy = model('Common/Buy', "logic");
        $result = $logic_buy->buyStep1($cart_id, $ifcart, $this->member_id, $this->store_id);
        if (! $result['status']) {
            $this->error($result['msg']);
        } else {
            $result = $result['data'];
        }
        
        // 商品金额计算(分别对每个商品/优惠套装小计、每个店铺小计)
        $this->assign('store_cart_list', $result['store_cart_list']);
        $this->assign('store_goods_total', $result['store_goods_total']);
        
        // 取得店铺优惠 - 满即送(赠品列表，店铺满送规则列表)
        $this->assign('store_premiums_list', $result['store_premiums_list']);
        $this->assign('store_mansong_rule_list', $result['store_mansong_rule_list']);
        
        // 返回店铺可用的代金券
        $this->assign('store_voucher_list', $result['store_voucher_list']);
        
        // 返回需要计算运费的店铺ID数组 和 不需要计算运费(满免运费活动的)店铺ID及描述
        $this->assign('need_calc_sid_list', $result['need_calc_sid_list']);
        $this->assign('cancel_calc_sid_list', $result['cancel_calc_sid_list']);
        
        // 将商品ID、数量、运费模板、运费序列化，加密，输出到模板，选择地区AJAX计算运费时作为参数使用
        $this->assign('freight_hash', $result['freight_list']);
        
        // 输出用户默认收货地址
        $this->assign('address_info', $result['address_info']);
        
        // 输出有线下支付时，在线支付和线下支付及每种支付下商品数量和详细列表
        $this->assign('pay_goods_list', $result['pay_goods_list']);
        $this->assign('ifshow_offpay', $result['ifshow_offpay']);
        $this->assign('deny_edit_payment', $result['deny_edit_payment']);
        
        // 不提供增值税发票时抛出true(模板使用)
        $this->assign('vat_deny', $result['vat_deny']);
        
        // 增值税发票哈希值(php验证使用)
        $this->assign('vat_hash', $result['vat_hash']);
        
        // 输出默认使用的发票信息
        $this->assign('inv_info', $result['inv_info']);
        
        // 显示预存款、支付密码、充值卡
        $this->assign('available_pd_amount', $result['available_predeposit']);
        $this->assign('member_paypwd', $result['member_paypwd']);
        $this->assign('available_rcb_amount', $result['available_rc_balance']);
        
        // 删除购物车无效商品
        $logic_buy->delCart($ifcart, $this->member_id, input('invalid_cart'));
        
        // 标识购买流程执行步骤
        
        $this->assign('ifcart', $_POST['ifcart']);
        
        // 店铺信息
        $store_list = $this->db_lists('store', [
            'id' => [
                'in',
                array_keys($result['store_cart_list'])
            ]
        ], [
            'field' => 'id,member_id,store_domain'
        ]);
        $this->assign('store_list', $store_list);
        
        return view('cart/step2');
    }
    
    // 订单生成页
    public function order()
    {
        $logic_buy = model('Common/Buy', "logic");
        $data = input('post.');
        $result = $logic_buy->buyStep2($data, $this->member_id, $this->member_info['name'], $this->member_info['email']);
        if ($result && $result['status']) {
            cookie('cart_goods_num', null, - 3600);
        } else {
            $this->error($result['msg'], 'member/cart/index');
        }
        
        // 转向到商城支付页面
        if ($data['from_step'] == 'step1') {
            return redirect(url('member/buy/pay?pay_sn=' . $result['data']['pay_sn'] . "&from_step=step1"));
        } else {
            return redirect(url('member/buy/pay?pay_sn=' . $result['data']['pay_sn']));
        }
    }
    
    // 订单支付
    public function pay()
    {
        $pay_sn = input('pay_sn');
        if (! preg_match('/^\d{18}$/', $pay_sn)) {
            $this->error('该订单不存在', 'member/order/index');
        }
        
        // 查询支付单信息
        $pay_info = rpc('common/common/one', [
            'order_pay',
            [
                'pay_sn' => $pay_sn,
                'buyer_id' => $this->member_id
            ]
        ]);
        if (empty($pay_info)) {
            $this->error('该订单不存在', 'member/order/index');
        }
        
        $this->assign('pay_info', $pay_info);
        
        // 取子订单列表
        $condition = array();
        $condition['pay_sn'] = $pay_sn;
        $condition['order_state'] = array(
            'in',
            array(
                ORDER_STATE_NEW,
                ORDER_STATE_PAY
            )
        );
        $condition['delete_state'] = 0;
        $order_list = $this->db_lists('order', $condition, 'order_id,order_state,payment_code,order_amount,rcb_amount,pd_amount,order_sn');
        if (empty($order_list)) {
            $this->error('未找到需要支付的订单', 'member/order/index');
        }
        
        // 重新计算在线支付金额
        $pay_amount_online = 0;
        $pay_amount_offline = 0;
        // 订单总支付金额(不包含线下支付)
        $pay_amount = 0;
        
        foreach ($order_list as $key => $order_info) {
            
            $payed_amount = floatval($order_info['rcb_amount']) + floatval($order_info['pd_amount']);
            // 计算相关支付金额
            if ($order_info['payment_code'] != 'offline') {
                if ($order_info['order_state'] == ORDER_STATE_NEW) {
                    $pay_amount_online += ncPriceFormat(floatval($order_info['order_amount']) - $payed_amount);
                }
                $pay_amount += floatval($order_info['order_amount']);
            } else {
                $pay_amount_offline += floatval($order_info['order_amount']);
            }
            
            // 显示支付方式与支付结果
            if ($order_info['payment_code'] == 'offline') {
                $order_list[$key]['payment_state'] = '线下付款';
            } else {
                $order_list[$key]['payment_state'] = '在线支付';
                if ($payed_amount > 0) {
                    $payed_tips = '';
                    if (floatval($order_info['rcb_amount']) > 0) {
                        $payed_tips = '充值卡已支付：￥' . $order_info['rcb_amount'];
                    }
                    if (floatval($order_info['pd_amount']) > 0) {
                        $payed_tips .= ' 预存款已支付：￥' . $order_info['pd_amount'];
                    }
                    $order_list[$key]['order_amount'] .= " ( {$payed_tips} )";
                }
            }
        }
        $this->assign('order_list', $order_list);
        
        // 如果线上线下支付金额都为0，转到支付成功页
        if (empty($pay_amount_online) && empty($pay_amount_offline)) {
            $url = url('member/buy/pay_ok') . "?pay_sn=" . $pay_sn . "&pay_amount=" . ncPriceFormat($pay_amount);
            return redirect($url);
        }
        
        // 输出订单描述
        if (empty($pay_amount_online)) {
            $order_remind = '下单成功，请及时付款与提交支付凭证，然后我们将尽快安排相应的服务！';
        } elseif (empty($pay_amount_offline)) {
            $order_remind = '请您及时付款，以便订单尽快处理！';
        } else {
            $order_remind = '部分商品需要在线支付，请尽快付款！';
        }
        $this->assign('order_remind', $order_remind);
        $this->assign('pay_amount_online', ncPriceFormat($pay_amount_online));
        $this->assign('pd_amount', ncPriceFormat($pd_amount));
        // 显示支付接口列表
        if ($pay_amount_online > 0) {
            $condition = array();
            $condition['payment_state'] = 1;
            $payment_list = $this->db_lists("payment", $condition, [], 'reset_by_key', 'payment_code');
            if (! empty($payment_list)) {
                unset($payment_list['predeposit']);
                unset($payment_list['offline']);
            }
            
            if (empty($payment_list)) {
                $this->error('暂未找到合适的支付方式', 'member/order/index');
            }
            
            $this->assign('payment_list', $payment_list);
        }
        
        // 标识 购买流程执行第几步
        $this->assign('step', 'step3');
        $this->assign('from_step', input('from_step'));
        return view('cart/step3');
    }
    
    // 加载收货信息
    public function load_addr()
    {
        $id = $this->request->get('id/d', 0);
        if ($id) {
            $result = rpc('common/common/delete', [
                'address',
                [
                    'address_id' => $id,
                    'member_id' => $this->member_id
                ]
            ]);
        }
        $address_list = $this->db_lists('address', [
            'member_id' => $this->member_id
        ]);
        $this->view->assign('address_list', $address_list);
        return view();
    }
    
    // 新的收货地址
    public function add_addr()
    {
        if (request()->isPost()) {
            $rule = [
                "true_name|真实名字" => "max:50",
                "area_id|所在地区" => "number",
                "city_id|所在地区" => "number",
                "area_info|所在地区" => "max:255",
                "address|详细地址" => "max:255",
                "tel_phone|手机号码" => "number",
                "mob_phone|固定电话" => "max:20"
            ];
            $data = [
                'member_id' => $this->member_id,
                'true_name' => $this->request->param('true_name/s'),
                'area_id' => $this->request->param('area_id/d'),
                'city_id' => $this->request->param('city_id/d'),
                'area_info' => $this->request->param('area_info/s'),
                'address' => $this->request->param('address/s'),
                'tel_phone' => $this->request->param('tel_phone/s'),
                'mob_phone' => $this->request->param('mob_phone/s')
            ];
            $validate = new Validate($rule);
            if (! $validate->check($data)) {
                // 验证不通过
                return json(array(
                    'state' => false,
                    'msg' => $validate->getError()
                ));
            }
            $insert_id = rpc('common/common/create', [
                'address',
                $data
            ]);
            
            if ($insert_id) {
                return json(array(
                    'state' => true,
                    'addr_id' => $insert_id
                ));
            } else {
                return json(array(
                    'state' => false,
                    'msg' => '保存地址失败'
                ));
            }
        }
        return view();
    }
    
    // 更换收货地址
    public function change_addr()
    {
        $logic_buy = model('Common/Buy', 'logic');
        $data = input('post.');
        
        $data = $logic_buy->changeAddr($data['freight_hash'], $data['city_id'], $data['area_id'], $this->member_id);
        if (! empty($data)) {
            return json($data);
        }
        return '';
    }
    
    
    
    /**
     * 支付成功页面
     */
    public function pay_ok()
    {
        $pay_sn = input('pay_sn');
        if (!preg_match('/^\d{18}$/', $pay_sn)) {
            $this->error('该订单不存在', 'member/order/index');
        }

        //查询支付单信息
        $model_order = model('Common/Order');
        $pay_info = $model_order->getOrderPayInfo(array('pay_sn' => $pay_sn, 'buyer_id' => $this->member_id));
        if (empty($pay_info)) {
            $this->error('该订单不存在', 'member/order/index');
        }
        $this->assign('pay_info', $pay_info);

        $this->assign('step', 'step4');
        return view('cart/step4');
    }
    
    // 发票信息
    public function load_inv()
    {
        $id = $this->request->get('id/d', 0);
        if ($id) {
            $result = rpc('common/common/delete', [
                'invoice',
                [
                    'inv_id' => $id,
                    'member_id' => $this->member_id
                ]
            ]);
        }
        $inv_list = $this->db_lists('invoice', [
            'member_id' => $this->member_id
        ]);
        $this->view->assign('inv_list', $inv_list);
        return view();
    }
    
    // 新增发票信息
    public function add_inv()
    {
        if (request()->isPost()) {
            $rule = [
                "inv_state|发票类型" => "number",
                "inv_title|发票抬头" => "max:50",
                "inv_content|发票内容" => "max:10"
            ];
            $inv_selet = $this->request->param('inv_title_select/s');
            $inv_title = $inv_selet == 'person' ? '个人' : $this->request->param('inv_title/s');
            $data = [
                'member_id' => $this->member_id,
                'inv_state' => $this->request->param('invoice_type'),
                'inv_title' => $inv_title,
                'inv_content' => $this->request->param('inv_content/s')
            ];
            //判断是否存在发票信息
            $is_exist = rpc('common/common/one', ['invoice',
                $data]);
            if(!empty($is_exist)){
                // 已存在发票信息
                return json(array(
                    'state' => false,
                    'msg' => '重复添加发票信息'
                ));
            }
            $validate = new Validate($rule);
            if (! $validate->check($data)) {
                // 验证不通过
                return json(array(
                    'state' => false,
                    'msg' => $validate->getError()
                ));
            }
            $insert_id = rpc('common/common/create', [
                'invoice',
                $data
            ]);
            if ($insert_id) {
                return json(array(
                    'state' => true,
                    'id' => $insert_id
                ));
            } else {
                return json(array(
                    'state' => false,
                    'msg' => '保存地址失败'
                ));
            }
        }
    }
}
